package com.hzjy.api.service.impl;

import cn.tign.hz.domain.signflow.ConfigInfo;
import cn.tign.hz.domain.signflow.IndivInfo;
import cn.tign.hz.domain.signflow.OrgEntity;
import cn.tign.hz.domain.signflow.RealNameCertification;
import cn.tign.hz.helper.AccountHelper;
import cn.tign.hz.helper.SealHelper;
import cn.tign.hz.helper.SignHelper;
import cn.tign.hz.helper.TokenHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzjy.api.mapper.BqUserMapper;
import com.hzjy.api.service.BqTokenService;
import com.hzjy.api.vo.*;
import com.hzjy.common.config.WXpayConfig;
import com.hzjy.common.constant.Constants;
import com.hzjy.common.core.domain.AjaxResult;
import com.hzjy.common.exception.CustomException;
import com.hzjy.common.exception.user.CaptchaExpireException;
import com.hzjy.common.utils.ApiUserUtils;
import com.hzjy.common.utils.MessageUtils;
import com.hzjy.common.utils.PageData;
import com.hzjy.common.utils.StringUtils;
import com.hzjy.common.utils.http.HttpUtils;
import com.hzjy.common.utils.sign.Md5Utils;
import com.hzjy.framework.manager.AsyncManager;
import com.hzjy.framework.manager.factory.AsyncFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BqUserServiceImpl {
    private static final Logger log = LoggerFactory.getLogger(BqUserServiceImpl.class);

    @Value("${MD5.key}")
    private String key;
    @Autowired
    private BqUserMapper bqUserMapper;
    @Autowired
    private BqTokenService bqTokenService;


    /**
     * 网页版登录，可以使用用户名，手机号，信用代码
     *
     * @param bqLoginBody
     * @return
     */
    public String loginByWebUP(BqLoginBody bqLoginBody) {
        BqUser bqUser = findByUserName(bqLoginBody.getUsername());
        BqUser byPhone = findByPhone(bqLoginBody.getUsername());
        BqLoginUser bqLoginUser = new BqLoginUser();
        if (StringUtils.isNull(bqUser)) { //判断是否存在
            if (StringUtils.isNull(byPhone)){
                throw new CustomException("用户名不存在");
            }
            bqLoginUser.setBqUser(byPhone);
        }
        if (StringUtils.isNotNull(bqUser)){
            bqLoginUser.setBqUser(bqUser);
        }
        //网页端账号与后台账号分离，不使用Spring security进行权限的限制
        String password = Md5Utils.hash(bqLoginBody.getPassword() + key);
        //System.out.println(password);
        if (bqLoginUser.getBqUser().getPassWord().equals(password)) {
            return bqTokenService.createToken(bqLoginUser); //创建token
        } else {
            throw new CustomException("密码错误");
        }
    }

    /**
     * 网页版 短信登录
     *
     * @param bqPhoneLoginBody
     * @return
     */
    public String loginByWebUD(BqPhoneLoginBody bqPhoneLoginBody) {
        BqUser bqUser = findByPhone(bqPhoneLoginBody.getPhone());
        BqLoginUser bqLoginUser = new BqLoginUser();
        bqLoginUser.setBqUser(bqUser);
        return bqTokenService.createToken(bqLoginUser); //创建token
    }

    /**
     * 网站注册
     *
     * @param bqRegisterBody
     */
    public void registerByWeb(BqRegisterBody bqRegisterBody) {
        PageData userData = new PageData();
        Map map = new HashMap<>();
        map.put("userName", bqRegisterBody.getUsername());
        String password = Md5Utils.hash(bqRegisterBody.getPassword() + key);
        log.info("注册md5密码:" + password);
        map.put("passWord", password);
        map.put("phone", bqRegisterBody.getPhone());
        map.put("type", "0");
        map.put("state", "0");
        map.put("createDate",new Date());
        if (StringUtils.isNotBlank(bqRegisterBody.getOpenId())){
            map.put("openId",bqRegisterBody.getOpenId());
        }
        userData.setMap(map);
        bqUserMapper.insertBpUser(userData);
    }

    //微信登录
    public Map loginByWeiXin(WxLogin wxLogin) {
        // 授权（必填）
        String grant_type = "authorization_code";

        String code = "";
        if (StringUtils.isNotEmpty(wxLogin.getCode())) {
            code = wxLogin.getCode();
        }
        Map hashMap = new HashMap();
        // 登录凭证不能为空
        if (StringUtils.isEmpty(code)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxLogin.getNickName(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        // 请求参数
        String params = "appid=" + WXpayConfig.APPID + "&secret=" + WXpayConfig.AppSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析相应内容（转换成json对象）
        net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(sr);

        log.info("--------json--------"+ json);
        // 用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        BqUser bqUser = bqUserMapper.findByOpenId(openid);
        if (bqUser != null) {
            if (StringUtils.isNotBlank(bqUser.getPhone())){
                hashMap.put("flag",true);
                BqLoginUser bqLoginUser = new BqLoginUser();
                bqLoginUser.setBqUser(bqUser);
                String token = bqTokenService.createToken(bqLoginUser);
                hashMap.put("token",token);
            }else {
                hashMap.put("flag",false);
            }
        }
        hashMap.put("openId",openid);
        return hashMap;
    }

    /**
     * 根据用户名获取用户
     *
     * @param userName
     * @return
     */
    public BqUser findByUserName(String userName) {
        return bqUserMapper.findByUserName(userName);
    }

    /**
     * 根据openid获取用户
     *
     * @param openid
     * @return
     */
    public BqUser findByOpenId(String openid) {
        return bqUserMapper.findByOpenId(openid);
    }

    /**
     * 根据手机号获取用户
     *
     * @param phone
     * @return
     */
    public BqUser findByPhone(String phone) {
        return bqUserMapper.findByPhone(phone);
    }

    /**
     * 根据用户ID获取用户
     *
     * @param userId
     * @return
     */
    public BqUser findByUserId(String userId) {
        return bqUserMapper.findByUserId(userId);
    }

    /**
     * 根据信用代码获取用户
     *
     * @param creditCode
     * @return
     */
    public BqUser findByCreditCode(String creditCode) {
        return bqUserMapper.findByCreditCode(creditCode);
    }

    /**
     * 查询修改个人资料的信息
     */
    public PageData findEditData(Long userId) {
        return bqUserMapper.findeditData(userId);
    }

    /**
     * 修改个人资料
     */
    public void submitEditData(BqUser bqUser) {
        if (StringUtils.isNotNull(bqUser.getNickName())){
            BqUser oldUser = bqUserMapper.findByNickName(bqUser.getNickName());
            if (oldUser != null){
                if (!oldUser.getUserId().equals(bqUser.getUserId())){
                    throw new CustomException("用户昵称已存在");
                }
            }
        }
        bqUserMapper.submitEditData(bqUser);
    }

    /**
     * 修改密码
     * @param bqRegisterBody
     */
    public void updatePassWord(BqRegisterBody bqRegisterBody) {
        BqUser byPhone = bqUserMapper.findByPhone(bqRegisterBody.getPhone());
        String password = Md5Utils.hash(bqRegisterBody.getNewPassWord() + key);
        byPhone.setPassWord(password);
        byPhone.setEmail(bqRegisterBody.getEmail());
        byPhone.setAvatar(bqRegisterBody.getAvatar());
        bqUserMapper.submitEditData(byPhone);
    }

    /**
     * 实名认证
     * @param bqUser
     */
    public void realNameAuthentication(BqUser bqUser) {
        BqUser bpUser = bqUserMapper.findByUserId(bqUser.getUserId().toString());
        JSONObject indivInfo = new JSONObject();
        JSONObject orgEntity = new JSONObject();
        if (bpUser.getType() == 1) {
            //企业基本信息
            //公司名称
            orgEntity.put("name",bqUser.getEnterpriseName());
            //orgEntity.setAgentIdNo();
            //orgEntity.setAgentName();
            //公司信用代码
            orgEntity.put("certNo",bqUser.getCreditCode());
            //公司法人身份证号
            orgEntity.put("legalRepCertNo",bqUser.getCardNum());
            //公司法人姓名
            orgEntity.put("legalRepName",bqUser.getFullName());

        } else if (bpUser.getType() == 0) {
            //个人基本信息
            indivInfo.put("bankCardNo",bpUser.getBankNum());
            indivInfo.put("certNo",bpUser.getCardNum());
            indivInfo.put("certType","INDIVIDUAL_CH_IDCARD");
            indivInfo.put("mobileNo",bpUser.getPhone());
            indivInfo.put("name",bpUser.getFullName());
            indivInfo.put("nationality","MAINLAND");
        }

        try {
            log.info("---------------------获取token start------------------------------");
            //设置token缓存
            TokenHelper.getTokenData();
            String[] users = new String[2];
            log.info("---------------------创建个人账号start-------------------------------");
            //生成签名
            JSONObject personAcctJson = AccountHelper.createPersonAcct("hzjy_user" + bpUser.getUserId(),
                    bpUser.getFullName(), "CRED_PSN_CH_IDCARD", bpUser.getCardNum(), bpUser.getPhone(), bpUser.getEmail());
            String acctId = personAcctJson.getString("accountId");
            users[0] = acctId;
            log.info("---------------------acctId1-------------------------------" + acctId);
            log.info("---------------------创建个人账号end-------------------------------");
            //个人
            if (bpUser.getType() == 1) {
                //企业
                log.info("---------------------创建机构账号start----------------------------------");
                JSONObject orgAcctJson = AccountHelper.createOrgAcct("hzjy_org" + bpUser.getUserId(),
                        acctId, bpUser.getEnterpriseName(), null, bpUser.getCreditCode());
                String orgId = orgAcctJson.getString("orgId");
                users[1] = orgId;
            }
            JSONObject realNameCertification = new JSONObject();
            //待认证账号Id
            realNameCertification.put("accountId",acctId);
            //接收实名认证链接短信通知的手机号
            realNameCertification.put("receiveUrlMobileNo",bpUser.getPhone());
            //个人基本信息
            realNameCertification.put("indivInfo",indivInfo);
            //企业基本信息
            realNameCertification.put("orgEntity",orgEntity);
            realNameCertification.put("authType","PSN_FACEAUTH_BYURL");

            //指定页面显示实名认证方式
            JSONArray availableAuthTypes = new JSONArray();
            availableAuthTypes.add("PSN_FACEAUTH_BYURL");
            availableAuthTypes.add("PSN_BANK4_AUTHCODE");
            availableAuthTypes.add("PSN_TELECOM_AUTHCODE");
            realNameCertification.put("availableAuthTypes",availableAuthTypes);

            JSONObject contextInfo = new JSONObject();
            //configInfo.setContextId(acctId);
            contextInfo.put("origin","BROWSER");
            contextInfo.put("notifyUrl",WXpayConfig.real_name_notify_url);
            contextInfo.put("redirectUrl",WXpayConfig.eQB_redirect_url);
            contextInfo.put("showResultPage",true);

            realNameCertification.put("contextInfo",contextInfo);

            log.info("---------------------开始实名认证 ----------------------------------");
            log.info("---------------------realNameCertification  ------------------------------" +realNameCertification.toString());
            JSONObject jsonObject = SignHelper.indivIdentity(realNameCertification);
            log.info("---------------------实名认证返回 -------------"+jsonObject.toString());
            log.info("---------------------实名认证结束 ----------------------------------");
            String flowId = jsonObject.getString("flowId");
            bpUser.setFlowId(flowId);
            log.info("---------------------flowId -------------" + flowId);
            log.info("---------------------bqUser -------------" + bpUser.toString());
            bqUserMapper.submitEditData(bpUser);
        }catch (Exception ex){
            log.error("=============调用E签宝API异常=================" + ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 根据流程id查询user
     * @param flowId
     * @return
     */
    public BqUser findByFlowId(String flowId) {
        return bqUserMapper.findByFlowId(flowId);
    }
}
